package com.heima.behavior.service.imp;

import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.behavior.service.ApUnlikeBehaviorService;
import com.heima.common.exception.CustException;
import com.heima.model.behavior.dtos.UnLikesBehaviorDTO;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @作者 Azer
 * @创建日期 2021/11/27 17:40
 **/
@Service
@Slf4j
public class ApUnlikeBehaviorServiceImpl implements ApUnlikeBehaviorService {

    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    @Override
    public ResponseResult unlikeBehavior(UnLikesBehaviorDTO dto) {

//        ApUnlikesBehavior apUnlikesBehavior=new ApUnlikesBehavior();



//        1. 校验参数 文章id不能为空  需要登录 不喜欢类型取值为 0 或 1
        ApUser apUser = AppThreadLocalUtils.getUser();
        if (apUser == null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST, "需要登录才能够进行该操作");
        }
//        2. 查询行为实体数据
        Integer apUserId = apUser.getId();
        ApBehaviorEntry apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(apUserId, dto.getEquipmentId());

        Query query=Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("entryId").is(apBehaviorEntry.getId()));
        ApUnlikesBehavior one = mongoTemplate.findOne(query, ApUnlikesBehavior.class);
//        3. 如果是 不喜欢操作 查询不喜欢行为是否存在
        if(dto.getType()==(short)0 && one==null){
//            4. 如果不存在   添加不喜欢行为

            one=new ApUnlikesBehavior();
            one.setEntryId(apBehaviorEntry.getId());
            one.setArticleId(dto.getArticleId());
            one.setType(dto.getType());
            one.setCreatedTime(new Date());

            mongoTemplate.save(one);
            log.info("添加不喜欢成功");
            return ResponseResult.okResult();
        }

//
//        5. 如果是 取消不喜欢操作  删除对应的不喜欢数据
        if(dto.getType()==(short)1){

            mongoTemplate.remove(query,ApUnlikesBehavior.class);
            log.info("取消不喜欢成功");
            return ResponseResult.okResult();

        }
        return null;
    }
}
